package com.liangtian.mdm.dm.jsp.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.dm.common.enums.Flag;
import com.liangtian.mdm.dm.common.page.JsonWrap;
import com.liangtian.mdm.dm.common.pojo.ResponseMsg;
import com.liangtian.mdm.dm.common.util.RequestUtils;
import com.liangtian.mdm.dm.config.model.AttrConfig;
import com.liangtian.mdm.dm.group.model.DataViewFlow;
import com.liangtian.mdm.dm.jsp.service.AutoCodeService;
import com.liangtian.mdm.dm.jsp.service.JspActionService;
import com.liangtian.mdm.dm.listener.CacheUtil;
import com.liangtian.mdm.dm.model.model.Model;
import com.liangtian.mdm.system.file.model.SysFile;
import com.liangtian.mdm.system.file.service.SysFileService;
import com.liangtian.mdm.system.user.service.SysUserService;
import com.liangtian.mdm.util.ExportUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/jspAction")
public class JspActionController extends BaseController {
    private static Logger log = LoggerFactory.getLogger(JspActionController.class);

    @Autowired
    private JspActionService jspActionService;

    @Autowired
    private CacheUtil cacheUtil;

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private AutoCodeService autoCodeService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 列表查询
     * 审核页面查询传递参数说明：
     * tableName  业务类型（业务类型新增时填写的）
     * operType='approve'（操作类型）
     * state=5 （数据状态）
     *
     * @param request
     * @return
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    @ResponseBody
    public String queryList(HttpServletRequest request) {  //JSONObject
        //查询条件
        Map<String, Object> param = RequestUtils.paramToMap(request);
//		System.out.println("=========queryList==========");
//		System.out.println(JSON.toJSONString(param));


        String shUser = String.valueOf(param.get("shApproveUser"));
        if (!StringUtils.isEmpty(shUser)) {
            List<String> userIds = null;//sysUserService.queryUsersIdByUserName(shUser);
            if (!CollectionUtils.isEmpty(userIds)) {
                param.put("shApproveUsers", userIds);
            }
        }

        PageInfo pageInfo = jspActionService.queryList(param);

        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);//JSONArray
        jsonObject.put("total", pageInfo.getTotal());//总记录数
        //return jsonObject;
        return JsonWrap.toJSONString(jsonObject);
    }

    /**
     * 生成的弹出框页面的查询方法
     * <p>TODO </p>
     * <p>@param request
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2018年1月2日下午12:50:12
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/queryPopList", method = RequestMethod.POST)
    @ResponseBody
    public String queryPopList(HttpServletRequest request) {  //JSONObject
        //查询条件
        Map<String, Object> param = RequestUtils.paramToMap(request);
//		System.out.println("=========queryList==========");
//		System.out.println(JSON.toJSONString(param));
        PageInfo pageInfo = jspActionService.queryPopList(param);

        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);//JSONArray
        jsonObject.put("total", pageInfo.getTotal());//总记录数
        //return jsonObject;
        return JsonWrap.toJSONString(jsonObject);
    }

    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/queryNoTabList", method = RequestMethod.POST)
    @ResponseBody
    public String queryNoTabList(HttpServletRequest request) {  //JSONObject
        //查询条件
        Map<String, Object> param = RequestUtils.paramToMap(request);
        PageInfo pageInfo = jspActionService.queryNoTabList(param);

        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);//JSONArray
        jsonObject.put("total", pageInfo.getTotal());//总记录数
        return JsonWrap.toJSONString(jsonObject);
    }

    /**
     * <p>TODO 查询数据视图分组权限 </p>
     * <p>@param request
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年5月8日下午2:27:14
     */
    @RequestMapping(value = "/queryDataViewFlows", method = RequestMethod.POST)
    @ResponseBody
    public String queryDataViewFlows(HttpServletRequest request) {  //JSONObject
        //查询条件
        List<DataViewFlow> resultLst = new ArrayList<DataViewFlow>();
        Map<String, Object> param = RequestUtils.paramToMap(request);
        List<DataViewFlow> viewLst = jspActionService.queryDataViewFlows(param);
        for (int i = 0; i < viewLst.size(); i++) {
            if (viewLst.get(i).getIsSelected().equals("1")) {//选中状态
                resultLst.add(viewLst.get(i));
            }
        }
        return JSON.toJSONString(resultLst);
    }

    /**
     * 查询单条数据信息
     * @param request
     * @return
     */
//	@RequestMapping(value = "/queryDataViewFlowsByDataId", method = RequestMethod.POST)
//    @ResponseBody
//	public String queryDataViewFlowsByDataId(HttpServletRequest request){
//		Map<String, Object> map = RequestUtils.paramToMap(request);
//		String sb="";
//        List<DataViewFlow> instanceLst = jspActionService.queryDataViewFlowsByDataId(map);
//        if(instanceLst.size()>0){
//        	for (int i = 0; i < instanceLst.size(); i++) {
//        		DataViewFlow daf = instanceLst.get(i);
//        		String groupId = daf.getGroupId();
//        		sb=sb+groupId+",";
//			}
//        	sb=sb.substring(0, sb.length()-1);
//        }
//		return sb.toString().trim();
//	}
//	

    /**
     * 数据删除
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject delete(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (ids == null || "".equals(ids))
            return null;

        Map<String, Object> map = new HashMap<>();
        //map.put("idList", ids.split(","));
        map.put("ids", ids);
        map.put("tableName", request.getParameter("tableName"));
        int ret = jspActionService.delete(map);
        int f = ret > 0 ? 1 : 0;
        ResultObject result = new ResultObject(f, "删除成功", "删除失败");
        return result;
    }


    /**
     * <p>TODO 导出数据  exportData</p>
     * <p>@param request
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年12月4日上午7:54:12
     */
    @RequestMapping(value = "/exportData", method = RequestMethod.GET)
    @ResponseBody
    public void exportData(HttpServletResponse response, HttpServletRequest request) {
        //获取参数modelId
        String modelId = request.getParameter("modelId");
        jspActionService.exportData(modelId, response);

    }


    /**
     * 查询模型表里面的数据
     */
    @RequestMapping(value = "/queryModelCount", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject queryModelCount(HttpServletRequest request) {
        String modelId = request.getParameter("modelId");
        Map<String, Object> map = new HashMap<>();
        String tableName = "T_" + modelId;
        map.put("modelId", modelId.trim());
        map.put("tableName", tableName.trim());
        int ret = jspActionService.queryModelCount(map);
        int f = ret > 0 ? 1 : 0;
        ResultObject result = new ResultObject(f, "模型里有数据,请先删除数据，在删除模型！", "模型可以删除！");
        return result;
    }


    @RequestMapping(value = "/check", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject check(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (ids == null || "".equals(ids))
            return null;

        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("tableName", request.getParameter("tableName"));

        int ret = jspActionService.check(map);
        int f = ret > 0 ? 1 : 0;
        ResultObject result = new ResultObject(f, "校验成功", "校验失败");
        return result;
    }

    /**
     * 新增数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject insert(HttpServletRequest request) {
        Map<String, Object> param = RequestUtils.paramToMap(request);
        //操作类型
        Object opertype = param.get("operType");
        String idValue = null;
        boolean ret = false;
        boolean isFile = false;
        int f = 0;
        String modelId = (String) param.get("modelId");
        List<AttrConfig> acLst = cacheUtil.getAttrList(modelId);
        Model model = cacheUtil.getModel(modelId);
        for (AttrConfig attrConfig : acLst) {
            if (attrConfig.getAttrType() != null && "BLOB".equals(attrConfig.getAttrType()))
                isFile = true;
        }
        // 变更、冻结、解冻
        if (Flag.OPER_1.getCode().equals(opertype)
                || Flag.OPER_3.getCode().equals(opertype)
                || Flag.OPER_4.getCode().equals(opertype)) {
            ret = jspActionService.insertBg(param);
            f = ret == true ? 1 : 0;
        } else if (Flag.OPER_5.getCode().equals(opertype)) {
            // 分发
            try {
                ret = jspActionService.insertDis(param);
            } catch (Exception e) {
                e.printStackTrace();
            }
            f = ret == true ? 1 : 0;
        } else {
            if ("updateAdd".equals(opertype)) {
                String mainId = param.get("mainId").toString();
                Map<String, Object> cond = new HashMap<>();
                cond.put("id", mainId);
                cond.put("modelId", modelId);
                cond.put("tableName", param.get("mainTableName").toString());
                Map<String, Object> mainMap = jspActionService.queryOne(cond);
                param.put("version", mainMap.get("version"));
                param.put("mainid", mainId);
            }
            Map<String, Object> result_map = jspActionService.insert(param);
            ret = (boolean) result_map.get("flag");
            f = ret == true ? 1 : 0;
            if (ret) {//新增数据成功，再保存附件
                if (isFile) {
                    Map<String, Object> Fcond = new HashMap<>();
                    String surveyName = model.getModelName();
                    ;
                    Fcond.put("surveyType", modelId);
                    Fcond.put("surveyName", surveyName);
                    Fcond.put("dataId", (String) result_map.get("idValue"));
                    Fcond.put("fileList", result_map.get("fileList"));
                    Fcond.put("operType", opertype);
                    Map<String, Object> FMap = sysFileService.insertFile(request, Fcond);
                    ret = (boolean) FMap.get("IsSuccess");
                    f = ret == true ? 1 : 2;
                }
            }
            idValue = (String) result_map.get("idValue");
        }
        ResultObject result = null;
        if (null != idValue) {//返回主表ID
            if (model.getIsMoreView() == 1) {//表示是多视图
                this.checkDataViewFlow(param, idValue);
            }
            result = new ResultObject(f, idValue, "新增失败");
        } else {
            result = new ResultObject(f, "新增成功", "新增失败");
        }
        return result;
    }

    /**
     * 编辑数据
     *
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject update(HttpServletRequest request) {
        Map<String, Object> param = RequestUtils.paramToMap(request);
        List<String> fileList = new ArrayList<String>();
        boolean isFile = false;
        int f = 0;
        String modelId = (String) param.get("modelId");
        List<AttrConfig> acLst = cacheUtil.getAttrList(modelId);
        Model model = cacheUtil.getModel(modelId);
        for (AttrConfig attrConfig : acLst) {
            //System.out.println(attrConfig.getAttrType());
            if ("BLOB".equals(attrConfig.getAttrType())) {
                fileList.add(attrConfig.getAttrColumn());
                isFile = true;
            }
        }
        if (isFile) {
            Map<String, Object> Fcond = new HashMap<>();
            String surveyName = model.getModelName();
            ;
            Fcond.put("surveyType", modelId);
            Fcond.put("surveyName", surveyName);
            Fcond.put("dataId", (String) param.get("id"));
            Fcond.put("operType", (String) param.get("operType"));
            System.out.println("*************************wyces****" + Fcond.get("dataId"));
            //当修改的时候，不上传新的附件，就不删除旧的附件
            List<SysFile> file = sysFileService.queryFileBySurvey(Fcond);
            Map<String, Object> FMap = sysFileService.insertFile(request, Fcond);
            List<String> fileNameLst = (List<String>) FMap.get("FileNameLst");
            if (!fileNameLst.isEmpty()) {
                if (!file.isEmpty()) {
                    sysFileService.delFileByPath(file);
                }
            }
            boolean flag = (boolean) FMap.get("IsSuccess");
            f = flag ? 1 : 2;
            if (flag) {
                boolean ret = jspActionService.update(param);
                f = ret ? 1 : 0;
            }
        } else {
            boolean ret = jspActionService.update(param);
            f = ret ? 1 : 0;
        }
        if (model.getIsMoreView() == 1) {//表示是多视图
            Map<String, Object> paramT = new HashMap<>();
            String operType = (String) param.get("operType");
            String dataId = (String) param.get("id");
            paramT.put("modelId", modelId);
            paramT.put("dataId", dataId);
            if (operType.equals("apply")) {
                jspActionService.deleteDataFlow(paramT);
                DataViewFlow viewFlow;
                String groupIds = (String) param.get("groupIds");//不是默认的属性组
                if (groupIds != null) {
                    groupIds = groupIds.substring(0, groupIds.length() - 1);
                    String[] groupArray = groupIds.split(",");
                    for (int i = 0; i < groupArray.length; i++) {
                        String groupIdCats = groupArray[i];
                        String[] groupIdCat = groupIdCats.split("_");
                        String groupId = groupIdCat[0];
                        String isSelected = groupIdCat[1];
                        viewFlow = new DataViewFlow();
                        viewFlow.setDataId(dataId);
                        viewFlow.setModelId(modelId);
                        viewFlow.setGroupId(groupId);
                        viewFlow.setIsSelected(isSelected);
                        viewFlow.setOperType("add");
                        jspActionService.insertDataFlow(viewFlow);
                    }
                }
            }
        }
        ResultObject result = new ResultObject(f, "修改成功", "修改失败");
        return result;
    }

    /**
     * 冻结、解冻
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/changeStatus", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject changeStatus(HttpServletRequest request) {
        Map<String, Object> param = RequestUtils.paramToMap(request);
        boolean ret = jspActionService.changeStatus(param);
        int f = ret ? 1 : 0;
        ResultObject result = new ResultObject(f, "操作成功", "操作失败");
        return result;
    }

    /**
     * 查询单条数据信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryOne", method = RequestMethod.POST)
    @ResponseBody
    public String queryOne(HttpServletRequest request) {
        Map<String, Object> map = RequestUtils.paramToMap(request);
        String tableName = (String) map.get("tableName");
        String modelId = tableName.split("_")[1];
        map.put("modelId", modelId);
        map.put("tableName", tableName + " t");
        Map<String, Object> instance = jspActionService.queryOne(map);
        return JSON.toJSONString(instance);
    }

    /**
     * 查询单条数据信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryDetail", method = RequestMethod.POST)
    @ResponseBody
    public String queryDetail(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> param = RequestUtils.paramToMap(request);
        String id = request.getParameter("id");
        map.put("id", id);
        map.put("tableName", request.getParameter("tableName"));
        Map<String, Object> instance = jspActionService.queryDetail(param);
        return JSON.toJSONString(instance);
    }

    /**
     * 提交
     * String tableName, @RequestParam("ids[]") List<String> ids
     *
     * @param
     * @return
     */
//     @RequestMapping(value = "/submit", method = RequestMethod.POST)
//     @ResponseBody
//     public ResultObject submit(@RequestBody List<TjForm> forms) {
// //		Map<String, Object> param = new HashMap<>();
// //		String ids = request.getParameter("ids");
// //		param.put("ids", ids);
// //		param.put("tableName", request.getParameter("tableName"));
//         //   	boolean ret = jspActionService.submit(param);TjForm[] forms
//
//         boolean ret = false;
//         String err = "提交失败!";
//         try {
//             ret = jspActionService.submitFlow(forms);
//         } catch (Exception e) {
//             err = e.getMessage();
//             e.printStackTrace();
//         }
//         int f = ret ? 1 : 0;
//         ResultObject result = new ResultObject(f, "提交成功!", err);
//         return result;
//     }

    /**
     * 针对万达定制化开发（物料分配）物料代码+库存组织合起来做唯一性校验
     * String tableName, @RequestParam("ids[]") List<String> ids
     * @param request
     * @return
     */
//	@RequestMapping(value = "/checkFromToWanDaWork", method = RequestMethod.POST)
//	@ResponseBody
//	public ResultObject checkFromToWanDaWork(@RequestBody List<TjForm> forms){
//
//		boolean ret = false;
//		String err = "校验失败!";
//		try {
//			ret = jspActionService.checkFromToWanDaWork(forms);
//		} catch (Exception e) {
//			err = e.getMessage();
//			e.printStackTrace();
//		}
//        ResultObject result = new ResultObject(ret, "校验成功!");
//		return result;
//	}


    /**
     * 提交(中国万达集团主数据工作流专用) String tableName, @RequestParam("ids[]") List<String>
     * ids
     *
     * @param
     * @return
     */
    // @RequestMapping(value = "/submitToWandaWorkflow", method = RequestMethod.POST)
    // @ResponseBody
    // public ResultObject submitToWandaOa(@RequestBody List<TjForm> forms) {
    //     boolean ret = false;
    //     String err = "提交失败!";
    //     try {
    //         ret = jspActionService.submitToWandaWorkflow(forms);
    //     } catch (Exception e) {
    //         err = e.getMessage();
    //         e.printStackTrace();
    //     }
    //     int f = ret ? 1 : 0;
    //     ResultObject result = new ResultObject(f, "提交成功!", err);
    //     return result;
    // }


    /**
     * 审核
     *
     * @param
     * @return
     */
//     @RequestMapping(value = "/approve", method = RequestMethod.POST)
//     @ResponseBody
//     public String approve(@RequestBody List<ShForm> forms) {
//         String retStr = "";
//         try {
//             SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
//             if (user == null) {//其他系统调用方法时，获取不到user
//                 String userId = "";
//             }
//             String userId = user.getUserId().toString();
//             retStr = jspActionService.approveFlow(forms, userId, "PC");
//         } catch (Exception e) {
// //			err = e.getMessage();
//             e.printStackTrace();
//         }
// //		int f = Integer.parseInt((String) map.get("state"));// ? 1 : 0;
// //		map.get("state");
// //        ResultObject result = new ResultObject(f, "审核成功!", err);
//
//         return JSON.toJSONString(retStr);
// //		return result;
//     }

    /**
     * 跳转到新增页面
     *
     * @param modelId
     * @param tableName
     * @return
     */
    @RequestMapping(value = "toAdd", method = RequestMethod.GET)
    public ModelAndView toAdd(int modelId, String tableName) {
        String viewName = "/am/" + tableName + "_add";
        view.setViewName(viewName);
        view.addObject("modelId", modelId);
        view.addObject("tableName", tableName);
        return view;
    }

    /**
     * 跳转到编辑页面
     *
     * @param modelId
     * @param tableName
     * @return
     */
    @RequestMapping(value = "toUpdate", method = RequestMethod.GET)
    public ModelAndView toUpdate(int modelId, String tableName) {
        String viewName = "/am/" + tableName + "_update";
        view.setViewName(viewName);
        view.addObject("modelId", modelId);
        view.addObject("tableName", tableName);
        return view;
    }

    /**
     * 跳转到列表页面
     *
     * @param modelId
     * @param tableName
     * @return
     */
    @RequestMapping(value = "toList", method = RequestMethod.GET)
    public ModelAndView toList(int modelId, String tableName) {
        String viewName = "/am/" + tableName + "_list";
        view.setViewName(viewName);
        view.addObject("modelId", modelId);
        view.addObject("tableName", tableName);
        return view;
    }

    /**
     * todo ： 导出当前操作模型的导入模板
     * 跳转到列表页面
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "tempExport", method = RequestMethod.GET)
    @ResponseBody
    public void templeExport(HttpServletResponse response, HttpServletRequest request) {
        String modelId = request.getParameter("modelId");
        jspActionService.templeExport(modelId, response);
    }

    /**
     * <p>TODO 在主表界面导出从表的收集数据模板操作</p>
     * <p>@param response
     * <p>@param request </p>
     *
     * @author : xiaoliu
     * @date :2018年1月31日下午4:14:34
     */
    @RequestMapping(value = "tempSubExport", method = RequestMethod.GET)
    @ResponseBody
    public void templeSubExport(HttpServletResponse response, HttpServletRequest request) {
        String modelId = request.getParameter("modelIdSub");
        jspActionService.templeExport(modelId, response);
    }

    /**
     * 跳转到列表页面(前台导入数据方法)
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "excelImport", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject excelImport(HttpServletResponse response, HttpServletRequest request) {
        ResultObject result = null;
        try {
            String modelId = request.getParameter("modelId");
            MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = mulRequest.getFile("excel");
            InputStream input = file.getInputStream();
            Map<String, Object> resMap = new HashMap<>();

            //获取建模的详细信息
            Model model = cacheUtil.getModel(modelId);

            if (model.getIsMoreView() == 1) {//表示是多视图
                //刘晶更改导入方法(目前先注释)
                resMap = jspActionService.excelSXSSWorkImport(modelId, input);
            } else {//表示是非多视图
                resMap = jspActionService.excelImport(modelId, input);
            }

            boolean success = (boolean) resMap.get("bool");
            if (success) {
                result = new ResultObject(success, "导入成功");
            } else {
                result = new ResultObject(success, (String) resMap.get("err_fileName"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("导入结束");
        return result;
    }

    @RequestMapping(value = "downLoadErr", method = RequestMethod.POST)
    @ResponseBody
    public void downLoadErr(HttpServletResponse response, HttpServletRequest request) {
        String fileName = request.getParameter("err_fileName");

        try {
            ExportUtil.getErrText(fileName, request, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
//    	String fileName = request.getParameter("err_fileName");
//    	log.info("---wangyue---jspAC--fileName--:"+fileName);	
//		String path = JspActionController.class.getProtectionDomain().getCodeSource()  
//                .getLocation().getPath();
////		String file=path.substring(0, path.indexOf("/WEB-INF/classes"))+"/error_text/"+fileName;
//		String file = JspUtil.getModelPath()+"/"+fileName;
////		System.out.println("file:"+file);
//		log.info("---wangyue---jspAC--path-:"+path);
//		log.info("---wangyue---jspAC--file-:"+file);	
//		try {
//			InputStream inStream = new FileInputStream(file);
//			//String fileName = "dzsxz_error.txt";
//			//解决中文文件名乱码问题
//			/*if(request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0)
//			fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
//			else*/
//			if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
//			     fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
//			}else{
//			     fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
//			}
//			response.reset();
//			response.setCharacterEncoding("UTF-8");
//			response.setContentType("application/octet-stream; charset=UTF-8");
//			response.addHeader("Content-Disposition",  "attachment;filename=\"" + fileName + "\"");
//			// 循环取出流中的数据
//			byte[] b = new byte[100];
//			int len;
//			OutputStream output=response.getOutputStream();
//			while ((len = inStream.read(b)) > 0)
//				output.write(b, 0, len);
//			
//			output.flush();
//			output.close();
//			inStream.close();
//			//result=new Result
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (UnsupportedEncodingException e) {
//			//e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
        //return result;
    }


//	@RequestMapping(value = "/queryBootSel", method = RequestMethod.POST)
//    @ResponseBody
//    public String queryBootSel(HttpServletRequest request){
//		//这两种返回类型是需要判断的,如果是关联的别的主数据的类型,返回到页面的应该是code/value形式的,则返回map,如果是类似与"是/否"这种属性则返回一个list
//		List<String> list = new ArrayList<String>();//返回list
//		Map<String,String> map = new HashMap<String,String>();//返回map
//		String code = request.getParameter("code");
//		String table = request.getParameter("mTable");
//		Map<String,Object> map1 = jspActionService.queryBootSel(table,code);
//		return JSON.toJSONString(list);
//    }

//	没用了....用来测试自动附码功能
//	@RequestMapping(value = "/autoCode", method = RequestMethod.POST)
//    @ResponseBody
//    public JSONObject autoCode(String seqName, int length){
//		System.out.println("abc");
//		request.getParameter("selCode");
//    	String code = jspActionService.autoCode(seqName, length);
//    	String rst = JSON.toJSONString(code);
//		autoCodeService.autoCode("1430","1003");
//		JSONObject jsonObject = new JSONObject();
//		jsonObject.put("data", "abc");
//    	return jsonObject;
//    }
//	

    /**
     * <p>Description: 校验唯一性</p>
     */
    @ResponseBody
    @RequestMapping(value = "/checkcolumnName", method = RequestMethod.POST)
    public JSONObject checkcolumnName(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            String tableName = request.getParameter("tableName");
            String column = request.getParameter("column");
            String id = request.getParameter("id");
            String value = request.getParameter("value");
            if (id != null && id != "") {
                map.put("id", id);
            }
            map.put("value", value);
            map.put("tableName", tableName);
            map.put("column", column);
            int count = jspActionService.checkcolumnName(map);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }


    /**
     * <p>Description: 数据视图校验</p>
     */
    @ResponseBody
    @RequestMapping(value = "/checkDataViewFlow", method = RequestMethod.POST)
    public JSONObject checkDataViewFlow(Map param, String idValue) {
        JSONObject jsonObject = new JSONObject();
        List<AttrConfig> jspLst = new ArrayList<AttrConfig>();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            String modelId = (String) param.get("modelId");
            DataViewFlow viewFlow;
            String groupIds = (String) param.get("groupIds");//不是默认的属性组
            if (groupIds != null) {
                groupIds = groupIds.substring(0, groupIds.length() - 1);
                String[] groupArray = groupIds.split(",");
                for (int i = 0; i < groupArray.length; i++) {
                    String groupIdCats = groupArray[i];
                    String[] groupIdCat = groupIdCats.split("_");
                    String groupId = groupIdCat[0];
                    String isSelected = groupIdCat[1];
                    viewFlow = new DataViewFlow();
                    viewFlow.setDataId(idValue);
                    viewFlow.setModelId(modelId);
                    viewFlow.setGroupId(groupId);
                    viewFlow.setIsSelected(isSelected);
                    viewFlow.setOperType("submit");
                    int count = jspActionService.insertDataFlow(viewFlow);
                    rMsg.setRspCode(count);
                }
            }
            //获取所有属性
            List<AttrConfig> attrConfigLst = cacheUtil.getAttrList(modelId);
            if (attrConfigLst.size() > 0) {
                for (int i = 0; i < attrConfigLst.size(); i++) {
                    AttrConfig config = attrConfigLst.get(i);
                    if (config.getGroupId().equals("") || config.getGroupId() == null) {
                        jspLst.add(config);
                    }
                }
            }
            if (jspLst.size() > 0) {//说明有默认属性
                viewFlow = new DataViewFlow();
                viewFlow.setDataId(idValue);
                viewFlow.setModelId(modelId);
                viewFlow.setGroupId("0");
                viewFlow.setIsSelected("1");
                viewFlow.setOperType("submit");
                jspActionService.insertDataFlow(viewFlow);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }


    /**
     * 生成xml格式字符串
     */
    @RequestMapping(value = "/creatXml", method = RequestMethod.POST)
    @ResponseBody
    public String creatXml(HttpServletRequest request) {  //JSONObject
        //查询条件

        Map<String, Object> param = RequestUtils.paramToMap(request);
        param.put("sysCode", "esbSys");
        Map<String, Object> data = jspActionService.creatXml(param);
        String dataStr = (String) data.get("XMLData");
        List<String> idLst = (List<String>) data.get("idLst");
        System.out.println(dataStr);
        System.out.println(idLst);
        return JSON.toJSONString(dataStr);
    }

    /**
     * <p>TODO  非物料模块添加冻结数据的归档功能，
     * 主要是是将冻结的数据删除，
     * 然后复制到相应的模块的归档表里，
     * 做一个数据备份的功能</p>
     * <p>@param request
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2018年4月6日下午6:48:02
     */
    @RequestMapping(value = "/gdData", method = RequestMethod.POST)
    @ResponseBody
    public String gdData(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            Map<String, Object> param = RequestUtils.paramToMap(request);
            List<String> ids = toList((String) param.get("ids"));
            String tableName = (String) param.get("tableName");
            param.put("idArray", ids);
            param.put("tableName", tableName);
            jspActionService.gdData(param);
            map.put("success", true);
        } catch (Exception e) { // TODO Auto-generated catch block
            e.printStackTrace();
            map.put("success", false);
            map.put("msg", e.getMessage());
        }
        return JSON.toJSONString(map);
    }

    /**
     * 传入一个ID字符串(以,号连接的),解析后,返回ID集合
     *
     * @param array
     * @return List<String>
     * @author jyh
     * @date 2016-09-27
     */
    public List<String> toList(String array) {
        ArrayList<String> list = new ArrayList<String>();
        if (array != null) {
            for (String string : array.split(",")) {
                list.add(string);
            }
        }
        return list;
    }
}